package cn.tedu.controller;

import javax.servlet.http.HttpSession;

import cn.tedu.pojo.User;
import cn.tedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * 用户控制器类
 */
@Controller
public class UserController {
    // 依赖注入
    @Autowired
    private UserService userService;
    /**
     * 用户登录
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public String login(String usercode,String password, Model model,
                        HttpSession session) {
        // 通过账号和密码查询用户
        User user = userService.findUser(usercode, password);
        if(user != null){
            // 将用户对象添加到Session
            session.setAttribute("USER_SESSION", user);
            // 跳转到主页面
//			return "customer";
            return "redirect:/productList.do";
        }
        model.addAttribute("msg", "账号或密码错误，请重新输入！");
        // 返回到登录页面
        return "login";
    }

	/*//模拟其他类中跳转到客户处理界面的方法
	@RequestMapping(value="/toCustomer.action" )
	public String toCustomer() {

		return "customer";
	}*/

    @RequestMapping(value = "/regist")
    public String regist(){
        return "reg";
    }

    @RequestMapping(value = "/doRegist",method = RequestMethod.POST)
    public String doregist(String usercode,String password,Model model){
        if (usercode==null&&password==null){
            model.addAttribute("msg", "用户名和密码不能为空！");
            return "reg";
        }
        User user = userService.regUser(usercode);
        if(user != null){
            model.addAttribute("msg", "此用户已存在！");
            return "reg";
        }
        userService.addUser(usercode,password);
        return "login";
    }


    //推出方法
    @RequestMapping(value="/logout.action")
    public String loginout(HttpSession session) {
        session.invalidate();
        //重定向到登陆界面
        return "redirect:login.action";
    }

    @RequestMapping(value="/login.do",method=RequestMethod.GET)
    public String tologin(HttpSession session) {
        session.invalidate();
        //重定向到登陆界面
        return "login";
    }


}

